<?php

namespace app\controllers;

use app\librarys\Fanso2oInteface;
use app\librarys\Huafeiduo;
use app\librarys\Inteface;
use app\librarys\Tools;
use app\models\Address;
use app\models\ApplyInstitution;
use app\models\Area;
use app\models\Card;
use app\models\GoodsVisitLog;
use app\models\Information;
use app\models\Institution;
use app\models\MallExceptionLog;
use app\models\MallFrontEnd;
use app\models\MallOperateLog;
use app\models\Manager;
use app\models\Order;
use app\models\Pay;
use app\models\User;
use app\models\Voucher;
use PHPQRCode\Constants;
use PHPQRCode\QRcode;
use Yii;
use yii\base\InvalidParamException;
use yii\helpers\Url;
use yii\web\Controller;
use app\models\Mall;
use app\models\Goods;
use app\models\Cart;

/**
 * 触屏版商城
 * Class MallMController
 * @package app\controllers
 */
class MallMController extends Controller
{
    public $enableCsrfValidation = false;
    public $layout = 'mall_m_layout';

    public function beforeAction($action)
    {
//        //跳转到维护页面
//        $frings = \Yii::$app->session->get('frings');
//        if($frings == null){
//            $frings = Yii::$app->request->get('frings');
//            if($frings != null){
//                \Yii::$app->session->set('frings',$frings);
//            }
//        }
//
//        if($frings == null) {
//            if ($action->id != 'warn-incomplete') {
//                return $this->redirect(['mall-m/warn-incomplete'])->send();
//            }
//            return parent::beforeAction($action);
//        }
//        //跳转到维护页面
//


        Mall::authWeixinUserInfo();

        $isRecordLog = \Yii::$app->params['isRecordLog'];
        $logId = '';
        if ($isRecordLog == true) {
            // 记录请求日志
            $institution_code = null;
            $institution_name = null;

            $logId = MallOperateLog::add(
                $action->controller->id,
                $action->id,
                $_GET,
                $_POST,
                Mall::getCurrentUserId(),
                Mall::getCurrentUserName(),
                $institution_code,
                $institution_name,
                $_SERVER['REMOTE_ADDR'],
                $_SERVER['HTTP_USER_AGENT'],
                $_SERVER['REQUEST_TIME']
            );
            \Yii::$app->session->set('request_mall_operate_log_id', $logId);
            \Yii::$app->session->set('request_mall_timestamp', Tools::getMillisecond());
        }

        Mall::setCurrentInstitution();

        //获取机构信息进行日志更新
        $currentInstitution = \Yii::$app->session->get(Mall::SessionKey_CurrentInstitution);
        if ($currentInstitution != null && $isRecordLog == true) {
            $institution_code = $currentInstitution['code'];
            $institution_name = $currentInstitution['name'];
            MallOperateLog::setInstitution($logId, $institution_code, $institution_name);
        }

        Mall::weixinAutoLogin();
        return parent::beforeAction($action);
    }

    public function runAction($id, $params = [])
    {
        try {
            return parent::runAction($id, $params);
        } catch (\Exception $ex) {
            $isRecordLog = \Yii::$app->params['isRecordLog'];
            if ($isRecordLog == true) {
                // 记录异常日志
                $logId = \Yii::$app->session->get('request_mall_operate_log_id');
                if ($logId != null) {
                    MallOperateLog::setException($logId, $ex);

                    $operateLog = MallOperateLog::getById($logId);
                    if ($operateLog != null) {
                        $currentInstitution = \Yii::$app->session->get(Mall::SessionKey_CurrentInstitution);

                        $institution_code = null;
                        $institution_name = null;

                        if ($currentInstitution != null) {
                            $institution_code = $currentInstitution['code'];
                            $institution_name = $currentInstitution['name'];
                        }

                        MallExceptionLog::add(
                            $operateLog->controllerId,
                            $operateLog->actionId,
                            $operateLog->getParams,
                            $operateLog->postParams,
                            $operateLog->userId,
                            $operateLog->userName,
                            $institution_code,
                            $institution_name,
                            $operateLog->remoteAddr,
                            $operateLog->httpUserAgent,
                            $operateLog->createDatetime,
                            $ex
                        );
                    }
                }
            }

            return $this->error($ex->getMessage());
        }
    }

    public function afterAction($action, $result)
    {
        $isRecordLog = \Yii::$app->params['isRecordLog'];
        if ($isRecordLog == true) {
            // 记录请求总共耗时(毫秒)
            $logId = \Yii::$app->session->get('request_mall_operate_log_id');
            if ($logId != null) {
                $time = Tools::getMillisecond();
                $time = $time - \Yii::$app->session->get('request_mall_timestamp');
                MallOperateLog::setDurationTime($logId, $time);
            }
        }

        return parent::afterAction($action, $result);
    }

    public function render($view, $params = [])
    {
        $currentInstitution = null;
        try {
            $currentInstitution = Mall::getCurrentInstitution();
        } catch (\Exception $e) {
            $currentInstitution = null;
        }
        $theme = $currentInstitution == null ? '' : $currentInstitution['theme_m'];
        try {
            if (empty($theme)) {
                return parent::render($view, $params);
            } else {
                return parent::render("theme-$theme/$view", $params);
            }
        } catch (InvalidParamException $ex) {
            return parent::render($view, $params);
        }
    }

    public function renderPartial($view, $params = [])
    {
        $currentInstitution = null;
        try {
            $currentInstitution = Mall::getCurrentInstitution();
        } catch (\Exception $e) {
            $currentInstitution = null;
        }
        $theme = $currentInstitution == null ? '' : $currentInstitution['theme_m'];
        try {
            if (empty($theme)) {
                return parent::renderPartial($view, $params);
            } else {
                return parent::renderPartial("theme-$theme/$view", $params);
            }
        } catch (InvalidParamException $ex) {
            return parent::renderPartial($view, $params);
        }
    }

    private function weixinLogin($returnUrl)
    {
        $currentUser = Mall::getCurrentUser();
        if ($currentUser == null) {
            $openid = Mall::getWeixinOpenid();
            $userList = User::getUserListByWxOpenid($openid);
            Mall::removeCurrentUser();
            Mall::removeCurrentUserTemp();
            Mall::removeWeixinLoginPhone();
            $phone = null;
            if (count($userList) > 0) {
                foreach ($userList as $user) {
                    if ($user['institution_code'] == Mall::getCurrentInstitutionCode()) {
//                        Mall::setCurrentUser($user);
                        Mall::setCurrentUserTemp($user);
                    }
                    if (!empty($user['phone'])) {
                        $phone = $user['phone'];
                    }
                }
            }

//            $currentUser = Mall::getCurrentUser();
            $currentUser = Mall::getCurrentUserTemp();
            if ($currentUser != null) {
                if ($currentUser['is_enabled'] == 0) {
                    throw new \Exception('此用户已被禁用!');
                }

                if (empty($currentUser['phone'])) {
                    if ($phone != null) {
                        $userWithPhone = User::getUserByPhone(Mall::getCurrentInstitutionCode(), $phone);
                        if ($userWithPhone != null) {
                            $userId = User::merge($userWithPhone['id'], $currentUser['id']);
                            $user = User::getUser($userId);
                            Mall::setCurrentUser($user);
                            return $this->redirect($returnUrl);
                        } else {
                            $header = Mall::getWeixinHeader();
                            $data = [
                                'id' => $currentUser['id'],
                                'code' => $currentUser['code'],
                                'name' => $currentUser['name'],
                                'institution_code' => $currentUser['institution_code'],
                                'phone' => $phone,
                                'isEnabled' => 1,
                                'remark' => '',
                                'wx_openid' => $currentUser['wx_openid'],
                                'header_url' => $header
                            ];
                            $userId = User::addUser($data)['userId'];
                            $user = User::getUser($userId);
                            Mall::setCurrentUser($user);
                            return $this->redirect($returnUrl);
                        }
                    } else {
                        return $this->redirect("bind-phone?return_url=$returnUrl");
                    }
                } else {
                    Mall::setCurrentUser($currentUser);
                    return $this->redirect($returnUrl);
                }
            } else {
                if ($phone == null) {
                    return $this->redirect("bind-phone?return_url=$returnUrl");
                } else {
                    Mall::setWeixinLoginPhone($phone);
                    $currentInstitution = Mall::getCurrentInstitution();
                    if ($currentInstitution != null) {
                        $userWithPhone = User::getUserByPhone(Mall::getCurrentInstitutionCode(), $phone);
                        if ($userWithPhone != null) {
                            if ($userWithPhone['is_enabled'] == 0) {
                                throw new \Exception('此用户已被禁用!');
                            }
                            $openid = Mall::getWeixinOpenid();
                            $header = Mall::getWeixinHeader();
                            $data = [
                                'id' => $userWithPhone['id'],
                                'code' => $userWithPhone['code'],
                                'name' => $userWithPhone['name'],
                                'institution_code' => Mall::getCurrentInstitutionCode(),
                                'phone' => $userWithPhone['phone'],
                                'isEnabled' => $userWithPhone['is_enabled'],
                                'remark' => $userWithPhone['remark'],
                                'wx_openid' => $openid,
                                'header_url' => $header
                            ];
                            $userId = User::addUser($data)['userId'];
                            $user = User::getUser($userId);
                            Mall::setCurrentUser($user);
                            return $this->redirect($returnUrl);
                        } else {
                            Mall::setWeixinLoginPhone($phone);
                            Mall::weixinLogin();
                            return $this->redirect($returnUrl);
                        }
                    }
                }
            }
        }
    }

    public function actionClearAll()
    {
        Yii::$app->session->removeAll();
    }

    public function actionIndex()
    {
        $institutionCode = Mall::getCurrentInstitutionCode();
        //轮播图
        $wap_fbanner = MallFrontEnd::getAdByIdentifier($institutionCode, 'wap-fbanner');
        //活动分类
        $extendCategoryList = MallFrontEnd::getGoodsExtendCategoryList($institutionCode);
        //热销产品
        $hotGoodsList = MallFrontEnd::getHotGoodsList($institutionCode);

        $bargainGoodsList = MallFrontEnd::getBargainTopGoodsListByInstitution($institutionCode);

        $integral = User::getUserIntegral(Mall::getCurrentUserId());
//        var_dump($hotGoosList);exit;
        //特价产品 isActivity=1 是否有
        $activityBargainList = MallFrontEnd::getActivityBargainList($institutionCode);
        //卡片
        $card = Mall::getCurrentCard();
        if ($card != null) {
            $cardGoodsList = Card::getCardSelectedGoodsById($card['id']);
            foreach ($cardGoodsList as &$item) {
                $images = Goods::getGoodsImage($item['goods_code'], 1);
                if (count($images) > 0) {
                    $item['image'] = $images[0]['image_url'];
                } else {
                    $item['image'] = '';
                }
            }
            $card['goods_list'] = $cardGoodsList;
        }

        return $this->render('index', [
            'integral_unit' => Mall::getCurrentInstitutionIntegralUnit(),
            'integral' => $integral,
            'wap_fbanner' => $wap_fbanner,
            'extendCategoryList' => $extendCategoryList,

            'hotGoodsList' => $hotGoodsList,
            'bargainGoodsList' => $bargainGoodsList,
            'activityBargainList' => $activityBargainList,
            'card' => $card,
        ]);
    }

    public function actionCategory()
    {
        $institutionCode = Mall::getCurrentInstitutionCode();
        $categoryList = MallFrontEnd::getGoodsCategoryLv1($institutionCode);

        foreach ($categoryList as &$item1) {
            $categoryLv2 = MallFrontEnd::getGoodsCategoryNextLv($institutionCode, $item1['code']);
            $item1['categoryLv2'] = $categoryLv2;
            foreach ($item1['categoryLv2'] as &$item2) {
                $item2['categoryLv3'] = MallFrontEnd::getGoodsCategoryNextLv($institutionCode, $item2['code']);
            }
        }
//        var_dump($categoryList[0]['categoryLv2'][0]);exit;
        return $this->render('category', [
            'categoryList' => $categoryList,
        ]);
    }

    //get-category-next-lv  获取下一级分类 （暂时不用）
    public function actionGetCategoryNextLv()
    {
        $institutionCode = Mall::getCurrentInstitutionCode();
        $parent_code = Yii::$app->request->post('parent_code');
        $categoryLv2 = MallFrontEnd::getGoodsCategoryNextLv($institutionCode, $parent_code);
//        var_dump($categoryLv2);exit;
        foreach ($categoryLv2 as &$item) {
            $item['categoryLv3'] = MallFrontEnd::getGoodsCategoryNextLv($institutionCode, $item['code']);
        }
        return $this->renderJson([
            'categoryLv2' => $categoryLv2,
        ]);
    }

    public function actionSearch()
    {
        $userId = Mall::getCurrentUserId();
        $userIntegral = null;
        if ($userId) {
            $userIntegral = User::getUserIntegral($userId);
        }

        return $this->render('search', ['userIntegral' => $userIntegral]);
    }

    //订单确认
    public function actionOrderForm()
    {
        $user = self::loginAuth();
        $institutionCode = Mall::getCurrentInstitutionCode();
        $userId = $user['id'];
        $cartGoodsList = MallFrontEnd::getCartSelected($userId);

        if (count($cartGoodsList) == 0) {
            return $this->redirect(['mall-m/cart', 'institution_code' => Mall::getCurrentInstitutionCode()]);
        }
        $defaultAddress = MallFrontEnd::getDefaultAddress($userId);
        $userIntegral = User::getUserIntegral($userId);
        //是否有跨境电商商品
        $is_crossborder = 0;
        $selling_price_crossborder = 0;
        foreach ($cartGoodsList as $cartGoods) {
            if ($cartGoods['is_crossborder'] == '1') {
                $is_crossborder = 1;
                $selling_price_crossborder = $cartGoods['selling_price'] + $selling_price_crossborder;
            }
        }

        return $this->render('order-form', [
            'cartGoodsList' => $cartGoodsList,
            'defaultAddress' => $defaultAddress,
            'userIntegral' => $userIntegral,
            'is_crossborder' => $is_crossborder,
            'selling_price_crossborder' => $selling_price_crossborder,
        ]);
    }

    //订单提交 order-submit-handle
    public function actionOrderSubmitHandle()
    {
        $user = self::loginAuth();
        $userId = $user['id'];

        $remark = Yii::$app->request->post('remark');
        $idcard_name = Yii::$app->request->post('idcard_name');
        $idcard_number = Yii::$app->request->post('idcard_number');
        $orderSubmitResult = MallFrontEnd::submitOrder($userId, $remark, $idcard_name, $idcard_number);

        return $this->renderJson(['orderSubmitResult' => $orderSubmitResult]);
    }

    //只生成订单 create-order-handle
    public function actionCreateOrderHandle()
    {
        $user = self::loginAuth();
        $userId = $user['id'];

        $remark = Yii::$app->request->post('remark');
        $idcard_name = Yii::$app->request->post('idcard_name');
        $idcard_number = Yii::$app->request->post('idcard_number');

        $createOrderResult = MallFrontEnd::createOrder($userId, $remark, $idcard_name, $idcard_number);

        return $this->renderJson(['createOrderResult' => $createOrderResult]);
    }

    //只支付订单 pay-order-handle
    public function actionPayOrderHandle()
    {
        $user = self::loginAuth();
        $userId = $user['id'];
        $orderId = Yii::$app->request->post('orderId');
        $payOrderResult = MallFrontEnd::payOrder($userId, $orderId);

        return $this->renderJson(['payOrderResult' => $payOrderResult]);
    }

    //取消订单 cancel-order-handle
    public function actionCancelOrderHandle()
    {
        self::loginAuth();
        $order_code = Yii::$app->request->post('order_code');
        $remark = Yii::$app->request->post('remark');
        $status = 1;
        $order = MallFrontEnd::getOrderByCode($order_code);
        $message = '';
        if ($order == false) {
            $message = '未找到此订单';
        } else {
            if ($order['status'] == '1') {
                $re_status = Order::cancelOrder($order_code, $remark);
//                var_dump($re_status);exit;
                // 0正常 20未找到此订单 21订单不能取消
                if ($re_status == '0') {
                    $message = '订单取消成功';
                    $status = 0;
                }
                if ($re_status == '20') {
                    $message = '未找到此订单';
                }
                if ($re_status == '21') {
                    $message = '订单不能取消';
                }

            } else {
                $message = '订单不能取消';
            }
        }
        return $this->renderJson([], $status, $message);
    }

    //调试用 test-order-handle
    public function actionTestOrderHandle()
    {
        exit;
        //http://integral.duolahe.com/mall-m/pay-order-success?isMix=1&out_trade_no=wx20160927154912853484
        $user = self::loginAuth();
        $userId = $user['id'];
        $orderCode = Yii::$app->request->post('orderCode');
        $cmd = \Yii::$app->db->createCommand('update t_order set status=1 where code=:orderCode');
        $cmd->bindValue(':orderCode', $orderCode);

        $cmd->execute();
        $cmd = \Yii::$app->db->createCommand('update t_user set integral=500 where id=:user_id');
        $cmd->bindValue(':user_id', $userId);

        $cmd->execute();
        return $this->renderJson([]);
    }

    //查询现金支付记录get-pay-integral-record-handle
    //修改为回调时候完成混合支付订单 2016-12-28
    public function actionGetPayIntegralRecordHandle()
    {
        self::loginAuth();
        $out_trade_no = Yii::$app->request->post('out_trade_no');
        $re = Pay::getPayIntegralRecord($out_trade_no);
        if ($re) {
//            支付状态
//            0：未支付
//            1：已支付
            return $this->renderJson(['cash_status' => $re['status']]);
        }
        return $this->renderJson([], 1, '没有这个现金支付订单');
    }

    //支付成功页面
    public function actionPayOrderSuccess($isMix = 0, $out_trade_no = '', $orderId = '')
    {
        $orderInfo = null;

        if ($orderId) {
            $orderInfo = MallFrontEnd::getOrderById($orderId);
            if ($orderInfo == false) {
                echo "order not found!1";
                exit;
            }

        }
        if ($out_trade_no) {
            $re = Pay::getPayIntegralRecord($out_trade_no);
            if ($re == false) {
                echo "order not found!2";
                exit;
            }
            $orderInfo = MallFrontEnd::getOrderByCode($re['order_code']);
            if ($orderInfo == false) {
                echo "order not found!3";
                exit;
            }
            $orderInfo['integral'] = $orderInfo['integral'] - $re['integral'];
            $orderInfo['total_fee'] = $re['total_fee'] / 100;
        }
        return $this->render('pay-order-success', [
            'isMix' => $isMix,
            'out_trade_no' => $out_trade_no,
            'orderInfo' => $orderInfo,
        ]);
    }

    public function actionOrderDetail($orderCode)
    {
        $user = self::loginAuth();
        $userId = $user['id'];

        $orderInfo = MallFrontEnd::getOrderByCode_detail($orderCode);
        if ($orderInfo == false) {
            echo "order not found!";
            exit;
        }
        $orderDeliveryList = [];
        $all_stock_status = 1;
        if ($orderInfo['status'] == '1') {//订单未支付
            /**
             * 更新未支付订单信息
             * ps:商品不能购买了:quantity数量设为0
             * ps:订单总价为0:订单状态设置为无效
             */
            MallFrontEnd::updateOrder($orderInfo['id']);
            //重新获取订单信息
            $orderInfo = MallFrontEnd::getOrderByCode_detail($orderCode);
            $orderGoodsList = MallFrontEnd::getOrderGoodsDetail($orderInfo['id'], $orderInfo['institution_code']);
            //库存信息/quantity
            foreach ($orderGoodsList as &$item) {
                $item['stock'] = MallFrontEnd::getGoodsStock($item['goods_code']);
                if ($item['stock'] < $item['quantity']) {
                    $all_stock_status = 0;
                }
            }
        } else {
            $orderGoodsList = MallFrontEnd::getOrderGoodsDetail($orderInfo['id'], $orderInfo['institution_code']);
            $orderDeliveryList = MallFrontEnd::getOrderDelivery($orderCode);
        }
//var_dump($orderInfo);exit;
        $orderInfo['orderStatusTxt'] = MallFrontEnd::orderStatusToUserTxt($orderInfo['status']);
        $userIntegral = User::getUserIntegral($userId);
        return $this->render('order-detail', [
            'orderInfo' => $orderInfo,
            'orderGoodsList' => $orderGoodsList,
            'orderDeliveryList' => $orderDeliveryList,
            'userIntegral' => $userIntegral,
            'all_stock_status' => $all_stock_status,

        ]);
    }

    public function actionDeliveryDetail()
    {
        $deliveryId = Yii::$app->request->get('delivery_id', null);

        $deliverydetail = null;
        if ($deliveryId != null && $deliveryId != '') {
            $deliverydetail = Order::getOrderDeliveryDetail($deliveryId);
            if ($deliverydetail != null && $deliverydetail != '') {
                $expressTrack = Inteface::getExpressTrackRecord($deliverydetail['logistics_code']);
                if ($expressTrack != null && $expressTrack != '') {
                    $deliverydetail['track_record'] = $expressTrack;
                } else {
                    $deliverydetail['track_record'] = [];
                }
            }
        }

        return $this->render('delivery-detail', ['item' => $deliverydetail]);
    }

    public function actionOrderList()
    {
        self::loginAuth();
        $userId = Mall::getCurrentUserId();
        $page = \Yii::$app->request->post('page', 1);
        $pageSize = \Yii::$app->request->post('page_size', 10000);
        $items = Order::getListByUser($userId, ($page - 1) * $pageSize, $pageSize);

        if ($items != null && $items != '') {
            for ($i = 0; $i < count($items); $i++) {
                $goodsitems = Order::getGoodsDetail($items[$i]['id']);
                if ($goodsitems != null && $goodsitems != '') {
                    $items[$i]['goods_list'] = $goodsitems;

                    $total_quantity = 0;
                    foreach ($goodsitems as $goods) {
                        $total_quantity = $total_quantity + $goods['quantity'];
                    }
                    $items[$i]['total_quantity'] = $total_quantity;
                } else {
                    $items[$i]['goods_list'] = null;
                    $items[$i]['total_quantity'] = null;
                }
            }
        }


        return $this->render('order-list', ['items' => $items]);
    }

    public function actionUserAddressList()
    {
        self::loginAuth();
        $items = Address::getUserAllAddress(Mall::getCurrentUserId());
        $isFromOrder = Yii::$app->request->get('is_from_order', 0);
        return $this->render('user-address-list', ['items' => $items, 'isFromOrder' => $isFromOrder]);
    }

    public function actionDeleteUserAddressHandler()
    {
        self::loginAuth();
        $addressId = Yii::$app->request->post('address_id');
        $status = Address::deleteAddress(Mall::getCurrentUserId(), $addressId);
        return $this->renderJson(null, $status);
    }

    public function actionSetDefaultUserAddressHandler()
    {
        self::loginAuth();
        $addressId = Yii::$app->request->post('address_id');
        $userId = Mall::getCurrentUserId();
        $status = Address::setDefault($userId, $addressId);
        return $this->renderJson(null, $status);
    }

    public function actionUserAddress()
    {
        self::loginAuth();
        $addressId = Yii::$app->request->get('address_id', null);
        $item = Address::getDetail($addressId);
        return $this->render('user-address', ['item' => $item]);
    }

    public function actionGetAreaHandler()
    {
        $parentId = Yii::$app->request->post('area_id', null);
        $items = Area::getAreaList($parentId);
        return $this->renderJson($items);
    }

    public function actionSetUserAddressHandler()
    {
        self::loginAuth();
        $addressId = Yii::$app->request->post('address_id');
        $name = Yii::$app->request->post('name');
        $phone = Yii::$app->request->post('phone');
        $provinceName = Yii::$app->request->post('province_name');
        $cityName = Yii::$app->request->post('city_name');
        $regionName = Yii::$app->request->post('region_name');
        $address = Yii::$app->request->post('address');
        $remark = Yii::$app->request->post('remark');

        $status = Address::saveAddress(Mall::getCurrentUserId(), $addressId, $name, $phone, $provinceName, $cityName, $regionName, $address, $remark);
        return $this->renderJson();
    }

    //添加商品到购物车 add-cart-handle
    public function actionAddCartHandle()
    {
        $user = self::loginAuth();
        $userId = $user['id'];
        $goodsCode = Yii::$app->request->post('goodsCode');
        $quantity = Yii::$app->request->post('quantity');
        $card_id = MallFrontEnd::addCart($userId, $goodsCode, $quantity);
        return $this->renderJson(['card_id' => $card_id]);
    }

    //修改某用户购物车中商品数 set-cart-quantity-handle
    public function actionSetCartQuantityHandle()
    {

        $user = self::loginAuth();
        $userId = $user['id'];
        $cartId = Yii::$app->request->post('cartId');
        $quantity = Yii::$app->request->post('quantity');
        MallFrontEnd::setCartQuantity($userId, $cartId, $quantity);
        return $this->renderJson([]);
    }

    //设置购物车商品选择状态 set-cart-selected-handle
    public function actionSetCartSelectedHandle()
    {

        $user = self::loginAuth();
        $userId = $user['id'];
        $cartId = Yii::$app->request->post('cartId');
        $isSelected = Yii::$app->request->post('isSelected');
        MallFrontEnd::setCartSelected($userId, $cartId, $isSelected);
        return $this->renderJson([]);
    }

    //移除某用户购物车中的某件商品 remove-cart-handle
    public function actionRemoveCartHandle()
    {

        $user = self::loginAuth();
        $userId = $user['id'];
        $cartId = Yii::$app->request->post('cartId');
        MallFrontEnd::removeCart($userId, $cartId);
        return $this->renderJson([]);
    }

    public function actionCart()
    {
        $institutionCode = Mall::getCurrentInstitutionCode();
        $user = Mall::getCurrentUser();
        $isLogin = false;
        $cartList = [];
        if ($user != null) {
            $userId = $user['id'];
            $isLogin = true;
            $cartList = MallFrontEnd::getCart($userId);
            //获取库存
            foreach ($cartList as &$item) {
                $item['stock'] = MallFrontEnd::getGoodsStock($item['goods_code']);
            }
//            var_dump($cartList);exit;
        }
        $hotGoosList = MallFrontEnd::getHotGoodsList($institutionCode);//热销产品
        return $this->render('cart', [
            'isLogin' => $isLogin,
            'hotGoosList' => $hotGoosList,
            'cartList' => $cartList,
        ]);
    }

    /**
     * 商品列表
     * @return string
     */
    public function actionGoodsListV1($page = 1, $pageSize = 10)
    {
        $institution_code = Mall::getCurrentInstitutionCode();//机构
        $page = is_numeric($page) ? $page : 1;
        $goodsListTitle = Yii::$app->request->get('goodsListTitle', '');//页面搜索标题
        //条件
        $goodsCode = Yii::$app->request->get('goodsCode', '');//产品代码
        $goodsName = Yii::$app->request->get('goodsName', '');//产品名称
        $goodsCategoryCode = Yii::$app->request->get('goodsCategoryCode', '');//商品类别
        $goodsExtendCategoryCode = Yii::$app->request->get('goodsExtendCategoryCode', '');//商品扩展类别
        $isActivity = Yii::$app->request->get('isActivity', '0');//是否活动产品
        $isNewest = Yii::$app->request->get('isNewest', null);//是否新品
        $isHot = Yii::$app->request->get('isHot', null);//是否热销
        $integralFrom = Yii::$app->request->get('integralFrom', null);//最小积分
        $integralTo = Yii::$app->request->get('integralTo', null);//最大积分
        //排序
        $sort = Yii::$app->request->get('sort', 0);//排序

        //取得产品总数
        $dataCount = MallFrontEnd::getGoodsListBySearch($institution_code, $goodsCode, $goodsName, $goodsCategoryCode, $goodsExtendCategoryCode, $isActivity, $isNewest, $isHot, $integralFrom, $integralTo, $sort);
//        var_dump($dataCount);exit;
        if ($dataCount % $pageSize > 0) {
            $maxPage = intval($dataCount / $pageSize) + 1;
        } else {
            $maxPage = intval($dataCount / $pageSize);
        }
        if ($page > $maxPage) {
            $page = $maxPage;
        }
        //查询结果
        $list = MallFrontEnd::getGoodsListBySearch($institution_code, $goodsCode, $goodsName, $goodsCategoryCode, $goodsExtendCategoryCode, $isActivity, $isNewest, $isHot, $integralFrom, $integralTo, $sort, false, $page, $pageSize);

        //返回结果
        return $this->render('goods-list-v1', [
            'items' => $list,
            'page' => $page,
            'maxPage' => $maxPage,
            'sort' => $sort,
            'goodsListTitle' => $goodsListTitle,
        ]);
    }

    /**
     * 商品列表
     * cv  展示形式
     * @return string
     */
    public function actionGoodsList($cv = 0)
    {
        $goodsListTitle = Yii::$app->request->get('goodsListTitle', '');//页面搜索标题
        //排序
        $sort = Yii::$app->request->get('sort', 0);//排序
        //返回结果
        return $this->render('goods-list-v2', [
            'goodsListTitle' => $goodsListTitle,
            'sort' => $sort,
            'cv' => $cv,
        ]);
    }

    public function actionGetGoodsListHandle($page = 1, $pageSize = 10)
    {
        $institution_code = Mall::getCurrentInstitutionCode();//机构
        $page = is_numeric($page) ? $page : 1;
        //条件
        $goodsCode = Yii::$app->request->get('goodsCode', '');//产品代码
        $goodsName = Yii::$app->request->get('goodsName', '');//产品名称
        $goodsCategoryCode = Yii::$app->request->get('goodsCategoryCode', '');//商品类别
        $goodsExtendCategoryCode = Yii::$app->request->get('goodsExtendCategoryCode', '');//商品扩展类别
        $isActivity = Yii::$app->request->get('isActivity', '0');//是否活动产品
        $isNewest = Yii::$app->request->get('isNewest', null);//是否新品
        $isHot = Yii::$app->request->get('isHot', null);//是否热销
        $integralFrom = Yii::$app->request->get('integralFrom', null);//最小积分
        $integralTo = Yii::$app->request->get('integralTo', null);//最大积分
        //排序
        $sort = Yii::$app->request->get('sort', 0);//排序

        //取得产品总数
        $dataCount = MallFrontEnd::getGoodsListBySearch($institution_code, $goodsCode, $goodsName, $goodsCategoryCode, $goodsExtendCategoryCode, $isActivity, $isNewest, $isHot, $integralFrom, $integralTo, $sort);
//        var_dump($dataCount);exit;
        $pageObject = MallFrontEnd::pageDo($dataCount, $page, $pageSize);
        $page = $pageObject[0];
        $maxPage = $pageObject[1];
        //查询结果
        $list = MallFrontEnd::getGoodsListBySearch($institution_code, $goodsCode, $goodsName, $goodsCategoryCode, $goodsExtendCategoryCode, $isActivity, $isNewest, $isHot, $integralFrom, $integralTo, $sort, false, $page, $pageSize);

        //返回结果
        $content_1 = $this->renderPartial('goods-list-content-1', [
            'items' => $list,
        ]);
        $content_2 = $this->renderPartial('goods-list-content-2', [
            'items' => $list,
        ]);
        return $this->renderJson([
            'content_1' => $content_1,
            'content_2' => $content_2,
            'page' => $page,
            'maxPage' => $maxPage,
            'sort' => $sort,
        ]);
    }

    /**
     * 商品详情
     * @return string
     */
    public function actionGoodsDetail()
    {
        $institutionCode = Mall::getCurrentInstitutionCode();//机构
        $goodsCode = \Yii::$app->request->get('goods_code');
        if (empty($goodsCode)) {
            echo 'goods_code error';
            exit;
        }
        $goods = MallFrontEnd::getGoodsDetail($institutionCode, $goodsCode);
        if ($goods) {
            // $goods['stock'] = MallFrontEnd::getGoodsStock($goodsCode);
        } else {
            echo 'goods_code not found!';
            exit;
        }
//        $hotGoosList = MallFrontEnd::getHotGoodsList($institutionCode);//热销产品
//        var_dump($goods);exit;
        //购物车商品数量
        $cartGoodsCount = 0;
        $user = Mall::getCurrentUser();
        $userId = null;
        if ($user) {
            $userId = $user['id'];
            $cartGoodsCount = MallFrontEnd::getCartGoodsCount($userId);
        }

        try {
            GoodsVisitLog::add($goodsCode, $userId, $institutionCode);  // 商品访问记录,以便统计商品受关注程度
        } catch (\Exception $e) {
        }

        return $this->render('goods-detail',
            [
                'goods' => $goods,
                'cartGoodsCount' => $cartGoodsCount,
                'institutionCode' => $institutionCode
            ]);
    }

    /**
     * 获取库存
     * get-goods-stock-handle
     */
    public function actionGetGoodsStockHandle()
    {
        $goodsCode = \Yii::$app->request->post('goodsCode');
        $stock = 0;
        if ($goodsCode) {
            $stock = MallFrontEnd::getGoodsStock($goodsCode);
        }

        return $this->renderJson($stock, 0, '');
    }

    /**
     * 获取历史足迹商品
     * @return string
     */
    public function actionGetHisGoodsHandler()
    {
        $institution_code = Mall::getCurrentInstitutionCode();//机构
        $goods_code_list = \Yii::$app->request->post('goods_code_list');
        $goods_codes = '';

        for ($i = 0; $i < count($goods_code_list); $i++) {
            $goods_codes = $goods_codes . '\'' . $goods_code_list[count($goods_code_list) - 1 - $i] . '\',';
        }

        $goods_codes = substr($goods_codes, 0, strlen($goods_codes) - 1);
        $items = MallFrontEnd::getHisGoodsList($institution_code, $goods_codes);
        return $this->renderJson($items, 0, '');
    }

    public function actionLogin()
    {
        $returnUrl = \Yii::$app->request->get('return_url', 'index?institution_code=' . Mall::getCurrentInstitutionCode());
        $returnUrl = urldecode($returnUrl);
        //$returnUrl = Tools::removeUrlParam($returnUrl, 'institution_code');

        if (strpos($_SERVER['HTTP_USER_AGENT'], "MicroMessenger")) {
            $this->weixinLogin($returnUrl);
        } else {
            if (\Yii::$app->request->isPost == true) {
                $phone = \Yii::$app->request->post('phone');
                $verificationCode = \Yii::$app->request->post('verification_code');
                $user = User::loginWithPhone(Mall::getCurrentInstitutionCode(), $phone, $verificationCode);
                if ($user != null) {
                    if ($user['is_enabled'] == 0) {
                        throw new \Exception('此用户已被禁用!');
                    }
                    Mall::setCurrentUser($user);
                    return $this->redirect($returnUrl);
                }
            }

            return $this->render('login', ['return_url' => urlencode($returnUrl)]);
        }
    }

    public function actionLogout()
    {
        Mall::userLogout();
        Mall::removeCurrentCard();
        Mall::removeCurrentVoucher();
        $returnUrl = \Yii::$app->request->get('return_url', 'index?institution_code=' . Mall::getCurrentInstitutionCode());
        return $this->redirect($returnUrl);
    }

    public function actionSendLoginSmsVerificationCodeHandler()
    {
        $phone = \Yii::$app->request->post('phone');
        try {
            $user = User::getUserByPhone(Mall::getCurrentInstitutionCode(), $phone);
            if ($user == null) {
                throw new \Exception('此机构无此用户!');
            }

            if ($user['is_enabled'] == 0) {
                throw new \Exception('此用户已被禁用!');
            }

            User::sendSmsVerificationCode($phone);
            return $this->renderJson();
        } catch (\Exception $ex) {
            return $this->renderJson(null, 1, $ex->getMessage());
        }
    }

    public function actionSendSmsVerificationCodeHandler()
    {
        $phone = \Yii::$app->request->post('phone');
        try {
            User::sendSmsVerificationCode($phone);
            return $this->renderJson();
        } catch (\Exception $ex) {
            return $this->renderJson(null, 1, $ex->getMessage());
        }
    }

    public function actionUserCenter()
    {
        $institution_code = Yii::$app->request->get('institution_code', false);
        $institution_code_param = '';
        if ($institution_code) {
            $institution_code_param = "institution_code=$institution_code&";
        }
        $user = Mall::getCurrentUser();
        if ($user == null) {
            $loginUrl = "login?{$institution_code_param}return_url=" . urlencode(Yii::$app->request->absoluteUrl);
            return $this->redirect($loginUrl);
        }

        $integral = User::getUserIntegral($user['id']);
        $integralUnit = Mall::getCurrentInstitutionIntegralUnit();

        return $this->render('user-center', ['user' => $user, 'integral' => $integral, 'integral_uint' => $integralUnit]);
    }

    public function actionAfterSaleService()
    {
        return $this->render('after-sale-service');
    }

    public function actionFeedback()
    {
        return $this->render('feedback');
    }

    public function actionCardSelect()
    {
        $openid = Mall::getWeixinOpenid();
        if ($openid == null) {
            throw new \Exception('请使用微信客户端打开重试');
        }
        $items = Card::getCardListByWeixinOpenid($openid);
        $institutions = [];
        foreach ($items as $item) {
            if (!in_array($item['institution_code'], $institutions)) {
                array_push($institutions, $item['institution_code']);
            }
        }
        if (count($institutions) == 1) {
            return $this->redirect(['index', 'institution_code' => $institutions[0]]);
        }
        return $this->render('card-select', ['items' => $items]);
    }

    public function actionInstitutionSelect()
    {
        $openid = Mall::getWeixinOpenid();
        if ($openid == null) {
            throw new \Exception('请使用微信客户端打开重试');
        }
        $items = User::getInstitutionListByWxOpenid($openid);
        if (count($items) == 1) {
            return $this->redirect(['index', 'institution_code' => $items[0]['institution_code']]);
        }
        return $this->render('institution-select', ['items' => $items]);
    }

    public function actionIntegralTransfer()
    {
        self::loginAuth();
        $integral = User::getUserIntegral(Mall::getCurrentUserId());
        return $this->render('integral-transfer', ['integral' => $integral]);
    }

    public function actionIntegralTransferHandler()
    {
        self::loginAuth();
        $msg = "";
        $flag = 0;
        $request = Yii::$app->request;
        $number = $request->post("number");
        $integral = $request->post("integral");


        $loginuser = Mall::getCurrentUser();
        if ($loginuser == null || $loginuser == '') {
            $flag = 1;
            $msg = "请先登陆";
        } else {

            if (($number != null && $number != '') && ($integral != null && $integral != '' && intval($integral) > 0)) {
                $into_user = User::getUserByPhone(Mall::getCurrentInstitutionCode(), $number);

                if ($number == $loginuser['phone']) {
                    $flag = 1;
                    $msg = "不能转增给自己";
                } else if ($into_user == null || $into_user == '') {
                    $flag = 1;
                    $msg = "对方用户不存在";
                } else if ($into_user['is_enabled'] == 0) {
                    $flag = 1;
                    $msg = "对方用户已被禁用";
                } else {
                    $rtvalue = User::integralTransfer($loginuser['id'], $into_user['id'], $integral);
                    if ($rtvalue == 1) {
                        $flag = 1;
                        $msg = "系统异常请重试";
                    } else if ($rtvalue == 20) {
                        $flag = 1;
                        $msg = "当前余额不足";
                    }
                }
            }
        }

        return $this->renderJson(null, $flag, $msg);
    }

    public function actionVoucherExchange()
    {
//        http://wx.duolahe.com/biz_weixin/web/index.php/wx-home/voucher-exchange?card_voucher=00000001&card_token=63252054
        $voucher = Yii::$app->request->get('card_voucher');
        $token = Yii::$app->request->get('card_token');

        Mall::removeCurrentVoucher();
        $voucherItem = Voucher::authVoucher($voucher, $token);
        Mall::setCurrentVoucher($voucherItem);

        Mall::removeCurrentCard();
        $card = Voucher::getCardByVoucher($voucher);
        if ($card == null) {
            Mall::removeCurrentVoucher();
            Mall::removeCurrentCard();
            throw new \Exception('卡片信息获取失败!');
        }
        Mall::setCurrentCard($card);

        return $this->redirect(['mall-m/card-bind-phone', "institution_code" => $card['to_institution_code']]);
    }

    public function actionBindPhone()
    {
        $returnUrl = Yii::$app->request->get('return_url');
        return $this->render('bind-phone', ['return_url' => $returnUrl]);
    }

    public function actionBindPhoneForm()
    {
        $phone = \Yii::$app->request->post('phone');
        $verificationCode = \Yii::$app->request->post('verification_code');
        $remarkName = Yii::$app->request->post('remark_name', '');
        $remarkPhone = Yii::$app->request->post('remark_phone', '');
        $remark = '推荐人姓名:' . $remarkName . '; 推荐人电话:' . $remarkPhone;
        $result = User::authSmsVerificationCode($phone, $verificationCode);
        if ($result == true) {
            $currentInstitution = Mall::getCurrentInstitution();
            if ($currentInstitution != null) {
                $userWithPhone = User::getUserByPhone(Mall::getCurrentInstitutionCode(), $phone);
                $openid = Mall::getWeixinOpenid();
                $userWithWeixin = User::getUserByWeixinOpenid(Mall::getCurrentInstitutionCode(), $openid);
                if ($userWithPhone != null && $userWithWeixin != null) {
                    $userId = User::merge($userWithPhone['id'], $userWithWeixin['id']);
                    $user = User::getUser($userId);
                    Mall::setCurrentUser($user);
                } else if ($userWithPhone != null) {
                    if ($userWithPhone['is_enabled'] == 0) {
                        throw new \Exception('此用户已被禁用!');
                    }
                    $openid = Mall::getWeixinOpenid();
                    $header = Mall::getWeixinHeader();
                    $data = [
                        'id' => $userWithPhone['id'],
                        'code' => $userWithPhone['code'],
                        'name' => $userWithPhone['name'],
                        'institution_code' => Mall::getCurrentInstitutionCode(),
                        'phone' => $userWithPhone['phone'],
                        'isEnabled' => $userWithPhone['is_enabled'],
                        'remark' => empty($remark) ? $userWithPhone['remark'] : $remark,
                        'wx_openid' => $openid,
                        'header_url' => $header
                    ];
                    $userId = User::addUser($data)['userId'];
                    $user = User::getUser($userId);
                    Mall::setCurrentUser($user);
                } else if ($userWithWeixin != null) {
                    if ($userWithWeixin['is_enabled'] == 0) {
                        throw new \Exception('此用户已被禁用!');
                    }
                    $openid = Mall::getWeixinOpenid();
                    $nickname = Mall::getWeixinNickname();
                    $header = Mall::getWeixinHeader();
                    $data = [
                        'id' => $userWithWeixin['id'],
                        'code' => $userWithWeixin['code'],
                        'name' => $nickname,
                        'institution_code' => Mall::getCurrentInstitutionCode(),
                        'phone' => $phone,
                        'isEnabled' => $userWithWeixin['is_enabled'],
                        'remark' => empty($remark) ? $userWithWeixin['remark'] : $remark,
                        'wx_openid' => $openid,
                        'header_url' => $header
                    ];
                    $userId = User::addUser($data)['userId'];
                    $user = User::getUser($userId);
                    Mall::setCurrentUser($user);
                } else {
                    Mall::setWeixinLoginPhone($phone);
                    Mall::weixinLogin($remark);
                }
            }
            $returnUrl = Yii::$app->request->post('returnUrl');
            if (empty($returnUrl)) {
                $returnUrl = 'index';
            }
            return $this->redirect($returnUrl);
        }
        $returnUrl = Yii::$app->request->post('returnUrl');
        return $this->render('bind-phone', ['return_url' => $returnUrl]);
    }

    public function actionBindPhoneSkipForm()
    {
        $currentUser = Mall::getCurrentUser();
        if ($currentUser == null) {
            $currentUserTemp = Mall::getCurrentUserTemp();
            if ($currentUserTemp == null) {
                $currentInstitution = Mall::getCurrentInstitution();
                if ($currentInstitution != null) {
                    Mall::weixinLogin();
                }
            } else {
                Mall::setCurrentUser($currentUserTemp);
            }
        }
        $returnUrl = Yii::$app->request->post('returnUrl');
        if (empty($returnUrl)) {
            $returnUrl = 'index';
        }
        return $this->redirect($returnUrl);
    }

    public function actionCardBindPhone()
    {
        $openid = Mall::getWeixinOpenid();
        if ($openid == null) {
            throw new \Exception('请使用微信客户端打开重试!');
        }

        $userList = User::getUserListByWxOpenid($openid);
        Mall::removeCurrentUser();
        $phone = null;
        if (count($userList) > 0) {
            foreach ($userList as $user) {
                if ($user['institution_code'] == Mall::getCurrentInstitutionCode()) {
                    Mall::setCurrentUser($user);
                }
                if (!empty($user['phone'])) {
                    $phone = $user['phone'];
                }
            }
        }

        $currentUser = Mall::getCurrentUser();

        if ($currentUser != null) {
            if ($currentUser['is_enabled'] == 0) {
                throw new \Exception('此用户已被禁用!');
            }

            if (!empty($currentUser['phone'])) {
                return $this->redirect('card-got');
            }

            if ($phone != null) {
                $userWithPhone = User::getUserByPhone(Mall::getCurrentInstitutionCode(), $phone);
                if ($userWithPhone != null) {
                    $userId = User::merge($userWithPhone['id'], $currentUser['id']);
                    $user = User::getUser($userId);
                    Mall::setCurrentUser($user);
                    return $this->redirect('card-got');
                } else {
                    $header = Mall::getWeixinHeader();
                    $data = [
                        'id' => $currentUser['id'],
                        'code' => $currentUser['code'],
                        'name' => $currentUser['name'],
                        'institution_code' => $currentUser['institution_code'],
                        'phone' => $phone,
                        'isEnabled' => 1,
                        'remark' => '',
                        'wx_openid' => $currentUser['wx_openid'],
                        'header_url' => $header
                    ];
                    $userId = User::addUser($data)['userId'];
                    $user = User::getUser($userId);
                    Mall::setCurrentUser($user);
                    return $this->redirect('card-got');
                }
            }
        } else {
            if ($phone != null) {
                $userWithPhone = User::getUserByPhone(Mall::getCurrentInstitutionCode(), $phone);
                if ($userWithPhone != null) {
                    if ($userWithPhone['is_enabled'] == 0) {
                        throw new \Exception('此用户已被禁用!');
                    }
                    $openid = Mall::getWeixinOpenid();
                    $header = Mall::getWeixinHeader();
                    $data = [
                        'id' => $userWithPhone['id'],
                        'code' => $userWithPhone['code'],
                        'name' => $userWithPhone['name'],
                        'institution_code' => Mall::getCurrentInstitutionCode(),
                        'phone' => $userWithPhone['phone'],
                        'isEnabled' => $userWithPhone['is_enabled'],
                        'remark' => $userWithPhone['remark'],
                        'wx_openid' => $openid,
                        'header_url' => $header
                    ];
                    $userId = User::addUser($data)['userId'];
                    $user = User::getUser($userId);
                    Mall::setCurrentUser($user);
                    return $this->redirect('card-got');
                } else {
                    $openid = Mall::getWeixinOpenid();
                    $nickname = Mall::getWeixinNickname();
                    $header = Mall::getWeixinHeader();
                    $data = [
                        'id' => '0',
                        'code' => '',
                        'name' => $nickname,
                        'institution_code' => Mall::getCurrentInstitutionCode(),
                        'phone' => $phone,
                        'isEnabled' => 1,
                        'remark' => '',
                        'wx_openid' => $openid,
                        'header_url' => $header
                    ];
                    $userId = User::addUser($data)['userId'];
                    $user = User::getUser($userId);
                    Mall::setCurrentUser($user);
                    return $this->redirect('card-got');
                }
            }
        }

        return $this->render('card-bind-phone');
    }

    public function actionCardBindPhoneForm()
    {
        $phone = \Yii::$app->request->post('phone');
        $verificationCode = \Yii::$app->request->post('verification_code');
        $result = User::authSmsVerificationCode($phone, $verificationCode);
        if ($result == true) {
//            $currentUser = Mall::getCurrentUser();
            $userWithPhone = User::getUserByPhone(Mall::getCurrentInstitutionCode(), $phone);
            $openid = Mall::getWeixinOpenid();
            $userWithWeixin = User::getUserByWeixinOpenid(Mall::getCurrentInstitutionCode(), $openid);
            if ($userWithPhone != null && $userWithWeixin != null) {
                User::merge($userWithPhone['id'], $userWithWeixin['id']);
            } else if ($userWithPhone != null) {
                if ($userWithPhone['is_enabled'] == 0) {
                    throw new \Exception('此用户已被禁用!');
                }
                $openid = Mall::getWeixinOpenid();
                $header = Mall::getWeixinHeader();
                $data = [
                    'id' => $userWithPhone['id'],
                    'code' => $userWithPhone['code'],
                    'name' => $userWithPhone['name'],
                    'institution_code' => Mall::getCurrentInstitutionCode(),
                    'phone' => $userWithPhone['phone'],
                    'isEnabled' => $userWithPhone['is_enabled'],
                    'remark' => $userWithPhone['remark'],
                    'wx_openid' => $openid,
                    'header_url' => $header
                ];
                $userId = User::addUser($data)['userId'];
                $user = User::getUser($userId);
                Mall::setCurrentUser($user);
            } else if ($userWithWeixin != null) {
                if ($userWithWeixin['is_enabled'] == 0) {
                    throw new \Exception('此用户已被禁用!');
                }
                $openid = Mall::getWeixinOpenid();
                $nickname = Mall::getWeixinNickname();
                $header = Mall::getWeixinHeader();
                $data = [
                    'id' => $userWithWeixin['id'],
                    'code' => $userWithWeixin['code'],
                    'name' => $nickname,
                    'institution_code' => Mall::getCurrentInstitutionCode(),
                    'phone' => $phone,
                    'isEnabled' => $userWithWeixin['is_enabled'],
                    'remark' => $userWithWeixin['remark'],
                    'wx_openid' => $openid,
                    'header_url' => $header
                ];
                $userId = User::addUser($data)['userId'];
                $user = User::getUser($userId);
                Mall::setCurrentUser($user);
            } else {
                $openid = Mall::getWeixinOpenid();
                $nickname = Mall::getWeixinNickname();
                $header = Mall::getWeixinHeader();
                $data = [
                    'id' => '0',
                    'code' => '',
                    'name' => $nickname,
                    'institution_code' => Mall::getCurrentInstitutionCode(),
                    'phone' => $phone,
                    'isEnabled' => 1,
                    'remark' => '',
                    'wx_openid' => $openid,
                    'header_url' => $header
                ];
                $userId = User::addUser($data)['userId'];
                $user = User::getUser($userId);
                Mall::setCurrentUser($user);
            }
//            $currentUser = Mall::getCurrentUser();
//            if ($currentUser == null) {
//                $openid = Mall::getWeixinOpenid();
//                $nickname = Mall::getWeixinNickname();
//                $header = Mall::getWeixinHeader();
//                $data = [
//                    'id' => '0',
//                    'code' => '',
//                    'name' => $nickname,
//                    'institution_code' => Mall::getCurrentInstitutionCode(),
//                    'phone' => $phone,
//                    'isEnabled' => 1,
//                    'remark' => '',
//                    'wx_openid' => $openid,
//                    'header_url' => $header
//                ];
//                $userId = User::addUser($data)['userId'];
//                $user = User::getUser($userId);
//                Mall::setCurrentUser($user);
//            } else {
//                $header = Mall::getWeixinHeader();
//                $data = [
//                    'id' => $currentUser['id'],
//                    'code' => $currentUser['code'],
//                    'name' => $currentUser['name'],
//                    'institution_code' => $currentUser['institution_code'],
//                    'phone' => $phone,
//                    'isEnabled' => 1,
//                    'remark' => '',
//                    'wx_openid' => $currentUser['wx_openid'],
//                    'header_url' => $header
//                ];
//                $userId = User::addUser($data)['userId'];
//                $user = User::getUser($userId);
//                Mall::setCurrentUser($user);
//            }
            return $this->redirect("card-got");
        }
        return $this->render('card-bind-phone');
    }

    public function actionCardBindPhoneSkipForm()
    {
        $currentUser = Mall::getCurrentUser();
        if ($currentUser == null) {
            $openid = Mall::getWeixinOpenid();
            $nickname = Mall::getWeixinNickname();
            $header = Mall::getWeixinHeader();
            $data = [
                'id' => '0',
                'code' => '',
                'name' => $nickname,
                'institution_code' => Mall::getCurrentInstitutionCode(),
                'phone' => null,
                'isEnabled' => 1,
                'remark' => '',
                'wx_openid' => $openid,
                'header_url' => $header
            ];
            $userId = User::addUser($data)['userId'];
            $user = User::getUser($userId);
            Mall::setCurrentUser($user);
        } else {
            $header = Mall::getWeixinHeader();
            $data = [
                'id' => $currentUser['id'],
                'code' => $currentUser['code'],
                'name' => $currentUser['name'],
                'institution_code' => $currentUser['institution_code'],
                'phone' => $currentUser['phone'],
                'isEnabled' => 1,
                'remark' => '',
                'wx_openid' => $currentUser['wx_openid'],
                'header_url' => $header
            ];
            $userId = User::addUser($data)['userId'];
            $user = User::getUser($userId);
            Mall::setCurrentUser($user);
        }
        return $this->redirect("card-got");
    }

    public function actionCardGot()
    {
        $voucher = Mall::getCurrentVoucher();
        $userId = Mall::getCurrentUserId();

        $voucherItem = Voucher::authVoucher($voucher['voucher'], $voucher['token']);

        if ($voucherItem['status'] == 3) {
            return $this->redirect("index");
        }

        if ($voucherItem['status'] == 2) {
            $status = Voucher::useVoucher($voucherItem['voucher'], $userId);
            if ($status != 0) {
                throw new \Exception('获取积分失败!');
            }
        }
        $institution = Mall::getCurrentInstitution();
        $qr = MallFrontEnd::getAdByIdentifier(Mall::getCurrentInstitutionCode(), 'weixin_qr');
        if (count($qr) > 0) {
            $qr = $qr[0]['image_url'];
        } else {
            $qr = null;
        }
        $card = Mall::getCurrentCard();
        return $this->render('card-got', ['institution' => $institution, 'card' => $card, 'qr' => $qr]);
    }

    private function error($error)
    {
        ob_clean();
        return $this->render('error', ['error' => $error]);
    }

    public function actionWarnIncomplete()
    {
        return $this->render('warn-incomplete');
    }

    /**
     * 蟹蟹有礼专题页面
     * @return string
     */
    public function actionXxyl()
    {
        return $this->render('special/xxyl');
    }

    /**
     * 秋季养生专题页面
     * @return string
     */
    public function actionQjys()
    {
        return $this->render('special/qjys');
    }

    /**
     * 环能德美服务包专题页面
     * @return string
     */
    public function actionHndmfwb()
    {
        return $this->render('special/hndmfwb');
    }


    public function renderJson($data = null, $status = 0, $message = 'success')
    {
        $result = [
            'status' => $status,
            'message' => $message,
            'data' => $data
        ];

        return json_encode($result, true);
    }

    private function loginAuth()
    {
        $user = Mall::getCurrentUser();
        if ($user == null) {

            if (strpos($_SERVER['HTTP_ACCEPT'], "application/json") === false) {

                $loginUrl = "login?return_url=" . urlencode(Yii::$app->request->absoluteUrl);
                // return $this->redirect($loginUrl);
                Header("Location:$loginUrl");
                exit;
            } else {
                $loginUrl = "login?return_url=" . urlencode($_SERVER['HTTP_REFERER']);
                echo $this->renderJson(['loginUrl' => $loginUrl], -1);
                exit;
            }

        }
//        var_dump($user);exit;
        return $user;
    }

    /**
     * 四川HR机构开通申请
     * @return string
     */
    public function actionApplyForInstitutionSchr()
    {
        return $this->render('apply-for-institution-schr');
    }

    /**
     * 上海锚定机构开通申请
     * @return string
     */
    public function actionApplyForInstitutionShmd()
    {
        return $this->render('apply-for-institution-shmd');
    }

    /**
     * 判断电话号码判断是否已经注册过
     * @return string
     */
    public function actionIsRegisterPhoneHandler()
    {
        $request = \Yii::$app->request;
        $phone = $request->post('txtContacterPhone');
        $result = Manager::existManager($phone);
        $data = null;
        if ($result != null) {
            $data =
                [
                    'account' => $phone,
                    'password' => '',
                    'record_id' => $result['record_id'],
                    'institution_code' => $result['institution_code']
                ];

        }

        return $this->renderJson($data, 0, '');
    }

    /**
     * 四川HR机构开通申请submit
     * @return string|\yii\web\Response
     */
    public function actionApplyForInstitutionSchrForm()
    {
        $data = null;
        $status = 0;
        $message = '';

        $request = \Yii::$app->request;
        $phone = $request->post('txtContacterPhone');
        $verificationCode = $request->post('txtVerificationCode');

        $phoneAuth = User::authSmsVerificationCode($phone, $verificationCode);
        if ($phoneAuth == true) {
            $applyData = $request->post();
            $applyData['parentCode'] = \Yii::$app->params['schr.institution.code']; // 创建机构(四川HR,parentCode固定为JG000002)
            if (Mall::applyForInstitution($applyData, $message, 'schr')) {
                $data =
                    [
                        'account' => $phone,
                        'password' => $applyData['password'],
                        'record_id' => $applyData['record_id'],
                        'institution_code' => $applyData['institution_code']
                    ];
            } else {
                $status = 1;
            }
        } else {
            $status = 1;
            $message = '验证码错误';
        }
        return $this->renderJson($data, $status, $message);
    }




    /**
     * 108人力资源福利平台
     * @return string
     */
    public function actionApplyForInstitutionYlb()
    {
        return $this->render('apply-for-institution-ylb');
    }


    /**
     * 108人力资源福利平台
     * @return string|\yii\web\Response
     */
    public function actionApplyForInstitutionYlbForm()
    {
        $data = null;
        $status = 0;
        $message = '';

        $request = \Yii::$app->request;
        $phone = $request->post('txtContacterPhone');
        $verificationCode = $request->post('txtVerificationCode');
        $phoneAuth = User::authSmsVerificationCode($phone, $verificationCode);
        if ($phoneAuth == true) {
            $applyData = $request->post();
            $applyData['parentCode'] = \Yii::$app->params['ylb.institution.code']; // 创建机构(108人力,parentCode固定为JG000002)
            if (Mall::applyForInstitution($applyData, $message, 'ylb')) {
                $data =
                    [
                        'account' => $phone,
                        'password' => $applyData['password'],
                        'record_id' => $applyData['record_id'],
                        'institution_code' => $applyData['institution_code']
                    ];
            } else {
                $status = 1;
            }
        } else {
            $status = 1;
            $message = '验证码错误';
        }
        return $this->renderJson($data, $status, $message);
    }

    public function actionApplyForInstitutionYlbSuccess()
    {
        $request = \Yii::$app->request;
        $account = $request->get('account');
        $password = $request->get('password');
        $record_id = $request->get('record_id');
        $institution_code = $request->get('institution_code');
        return $this->render('apply-for-institution-ylb-success',
            [
                'account' => $account,
                'password' => $password,
                'record_id' => $record_id,
                'institution_code' => $institution_code
            ]);
    }

    public function actionApplyForInstitutionYlbHelp()
    {
        $record_id = \Yii::$app->request->get('record_id');
        $item = ApplyInstitution::get($record_id);
        $institution_code = '';
        $account = '';
        if ($item != null) {
            $institution_code = $item['institution_code'];
            $account = $item['contacter_phone'];
        }
        return $this->render('apply-for-institution-ylb-help',
            [
                'institution_code' => $institution_code,
                'account' => $account
            ]);
    }



    /**
     * 上海锚定机构开通申请submit
     * @return string|\yii\web\Response
     */
    public function actionApplyForInstitutionShmdForm()
    {
        $data = null;
        $status = 0;
        $message = '';

        $request = \Yii::$app->request;
        $phone = $request->post('txtContacterPhone');
        $verificationCode = $request->post('txtVerificationCode');

        $phoneAuth = User::authSmsVerificationCode($phone, $verificationCode);
        if ($phoneAuth == true) {
            $applyData = $request->post();
            $applyData['parentCode'] = \Yii::$app->params['shmd.institution.code']; // 创建机构(上海锚定)
            if (Mall::applyForInstitution($applyData, $message, 'shmd')) {
                $data =
                    [
                        'account' => $phone,
                        'password' => $applyData['password'],
                        'record_id' => $applyData['record_id'],
                        'institution_code' => $applyData['institution_code']
                    ];
            } else {
                $status = 1;
            }
        } else {
            $status = 1;
            $message = '验证码错误';
        }
        return $this->renderJson($data, $status, $message);
    }

    public function actionApplyForInstitutionSuccess()
    {
        $request = \Yii::$app->request;
        $account = $request->get('account');
        $password = $request->get('password');
        $record_id = $request->get('record_id');
        $institution_code = $request->get('institution_code');

        return $this->render('apply-for-institution-success',
            [
                'account' => $account,
                'password' => $password,
                'record_id' => $record_id,
                'institution_code' => $institution_code
            ]);
    }

    public function actionApplyForInstitutionHelp()
    {
        $record_id = \Yii::$app->request->get('record_id');
        $item = ApplyInstitution::get($record_id);
        $institution_code = '';
        $account = '';
        if ($item != null) {
            $institution_code = $item['institution_code'];
            $account = $item['contacter_phone'];
        }
        return $this->render('apply-for-institution-help',
            [
                'institution_code' => $institution_code,
                'account' => $account
            ]);
    }


    /**
     * 恒游机构开通申请
     * @return string
     */
    public function actionApplyForInstitutionHy()
    {
        return $this->render('apply-for-institution-hy');
    }


    /**
     * 恒游机构开通申请submit
     * @return string|\yii\web\Response
     */
    public function actionApplyForInstitutionHyForm()
    {
        $data = null;
        $status = 0;
        $message = '';

        $request = \Yii::$app->request;
        $phone = $request->post('txtContacterPhone');
        $verificationCode = $request->post('txtVerificationCode');
        $phoneAuth = User::authSmsVerificationCode($phone, $verificationCode);
        if ($phoneAuth == true) {
            $applyData = $request->post();
            $applyData['parentCode'] = \Yii::$app->params['hy.institution.code']; // 创建机构(恒游,parentCode固定为JG000002)
            if (Mall::applyForInstitution($applyData, $message, 'hy')) {
                $data =
                    [
                        'account' => $phone,
                        'password' => $applyData['password'],
                        'record_id' => $applyData['record_id'],
                        'institution_code' => $applyData['institution_code']
                    ];
            } else {
                $status = 1;
            }
        } else {
            $status = 1;
            $message = '验证码错误';
        }
        return $this->renderJson($data, $status, $message);
    }

    public function actionApplyForInstitutionHySuccess()
    {
        $request = \Yii::$app->request;
        $account = $request->get('account');
        $password = $request->get('password');
        $record_id = $request->get('record_id');
        $institution_code = $request->get('institution_code');
        return $this->render('apply-for-institution-hy-success',
            [
                'account' => $account,
                'password' => $password,
                'record_id' => $record_id,
                'institution_code' => $institution_code
            ]);
    }

    public function actionApplyForInstitutionHyHelp()
    {
        $record_id = \Yii::$app->request->get('record_id');
        $item = ApplyInstitution::get($record_id);
        $institution_code = '';
        $account = '';
        if ($item != null) {
            $institution_code = $item['institution_code'];
            $account = $item['contacter_phone'];
        }
        return $this->render('apply-for-institution-hy-help',
            [
                'institution_code' => $institution_code,
                'account' => $account
            ]);
    }


    /**
     * 机构开通申请(通用)
     * @return string
     */
    public function actionApplyForInstitution()
    {
        return $this->render('apply-for-institution');
    }


    /**
     * 机构开通申请submit(通用)
     * @return string|\yii\web\Response
     */
    public function actionApplyForInstitutionForm()
    {
        $request = Yii::$app->request;
        $phone = $request->post('txtContacterPhone');
        $verificationCode = $request->post('txtVerificationCode');

        //根据电话号码判断是否已经注册过,注册过的直接跳转到成功页面123
        $result = Manager::existManager($phone);
        if ($result != null) {
            return $this->render('apply-for-institution-success',
                [
                    'account' => $phone,
                    'password' => '',
                    'record_id' => $result['record_id'],
                    'institution_code' => $result['institution_code']
                ]);
        }

        $phoneAuth = User::authSmsVerificationCode($phone, $verificationCode);
        if ($phoneAuth == true) {
            $applyData = $request->post();
            $applyData['parentCode'] = '0'; // 创建机构(通用的parentCode固定为0)
            Mall::applyForInstitution($applyData);
            return $this->render('apply-for-institution-success',
                [
                    'account' => $phone,
                    'password' => $applyData['password'],
                    'record_id' => $applyData['record_id'],
                    'institution_code' => $applyData['institution_code']
                ]);
        }
        return $this->redirect('apply-for-institution-schr');
    }


    public function actionVirtualCouponList($page = 1, $pageSize = 10, $tagName = 'all')
    {
        if ($tagName == 'all') {
            $result = Fanso2oInteface::helper_getAllGoodsList($page, $pageSize);
        } else {
            $result = Fanso2oInteface::helper_getCategoryGoodsList($tagName, $page, $pageSize);
        }
//        var_dump($goodsList);        exit;
        return $this->render('virtual-coupon-list', [
            'result' => $result,
        ]);
    }

    public function actionVirtualCouponDetail($shopId)
    {
        $goodsList = Fanso2oInteface::helper_getGoodsListByShopIdList([$shopId]);
        if (count($goodsList) == 0) {
            throw new \Exception("没有此卡券");
        }
        $goods = $goodsList[0];
        //适用地区
        $districtList = [];
        foreach ($goods['info']->district as $item) {
            $districtList[] = $item->name;
        }
        $goods['districtStr'] = implode(',', $districtList);
//        var_dump($goodsList);        exit;
        return $this->render('virtual-coupon-detail', [
            'goods' => $goods,
        ]);
    }

    public function actionGameList()
    {
        return $this->render('game-list');
    }

    public function actionPlayGamePayIntegralHandler()
    {
        $this->loginAuth();

        $integral = 1;
        $status = User::payUserIntegral(Mall::getCurrentUserId(), $integral, 8, '玩游戏消费1积分。');
        return $this->renderJson(null, $status);
    }

    public function actionPlayLotteryPayIntegralHandler()
    {
        $this->loginAuth();

        $integral = 1;
        $status = User::payUserIntegral(Mall::getCurrentUserId(), $integral, 9, '抽奖消费1积分。');
        return $this->renderJson(null, $status);
    }

    public function actionLotteryZp()
    {
        return $this->render('lottery/zp');
    }

    public function actionUserIntegralRecord()
    {
        $user = self::loginAuth();
        $userId = $user['id'];
        return $this->render('user-integral-record');
    }

    //user-integral-record-handle
    public function actionUserIntegralRecordHandle($page = 1, $pageSize = 10)
    {
        $user = self::loginAuth();
        $userId = $user['id'];
        $dataCount = MallFrontEnd::getUserIntegralRecord($userId, true);
        $pageObject = MallFrontEnd::pageDo($dataCount, $page, $pageSize);
        $page = $pageObject[0];
        $maxPage = $pageObject[1];

        $items = MallFrontEnd::getUserIntegralRecord($userId, false, $page, $pageSize);
        $result = [];
        foreach ($items as $item) {
            $typeAndRemark = MallFrontEnd::caseUserIntegralRecordTypeAndRemark($item['record_type'], $item['origin_id']);
            $result[] = [
                'type' => $typeAndRemark[0],
                'remark' => $typeAndRemark[1],
                'integral' => $item['integral'],
                'time' => $item['create_datetime'],
            ];
        }
        //返回结果
        $content = $this->renderPartial('user-integral-record-content', [
            'items' => $result,
        ]);
        return $this->renderJson([
            'content' => $content,
            'page' => $page,
            'maxPage' => $maxPage,
        ], 0);
    }

    /**
     * 手机话费充值
     * @return string
     */
    public function actionPhoneRecharge()
    {
        return $this->render('phone-recharge');
    }

    public function actionPhoneRechargeHandler()
    {
        $phone = Yii::$app->request->post('phone');
        $huafeiduo = new Huafeiduo();
        $result = $huafeiduo->check(1, $phone);
        if ($result == false) {
            return $this->renderJson(null, 1, '此手机不能进行充值');
        }
        $result = $huafeiduo->submit(1, $phone, $phone . time());
        if ($result == false) {
            return $this->renderJson(null, 2, '充值失败');
        }

        return $this->renderJson(null);
    }

    /**
     * 获取购物车产品数量
     * get-cart-goods-count
     */
    public function actionGetCartGoodsCount()
    {
        $cartGoodsCount = 0;
        $user = Mall::getCurrentUser();
        $userId = null;
        if ($user) {
            $userId = $user['id'];
            $cartGoodsCount = MallFrontEnd::getCartGoodsCount($userId);
        }
        return $this->renderJson([$cartGoodsCount]);
    }

    public function actionBsAndroidIphoneDownload()
    {
        return $this->renderPartial('bs-android-iphone-download');
    }

    //qr-code-out
    //输出二维码图片
    // //加入缓存机制，提速
    public function actionQrCodeOut($text = '', $size = 3, $margin = 4, $isCache = false)
    {
        if ($isCache == false) {
            QRcode::png($text, false, Constants::QR_ECLEVEL_L, $size, $margin);
            exit;
        } else {
            $path = Yii::$app->basePath . '/web/qrCache/';
            if (is_dir($path) == false)
                mkdir($path);
            $token_filename = md5("$text - $size - $margin") . '.png';
            $full_filename = $path . $token_filename;
            if (file_exists($full_filename) == false) {
                QRcode::png($text, $full_filename, Constants::QR_ECLEVEL_L, $size, $margin);
            }
            // 以二进制格式打开文件
            $fp = fopen($full_filename, 'rb');
            // 发送合适的报头
            header("Content-Type: image/png");
            header("Content-Length: " . filesize($full_filename));
            // 发送图片并终止脚本
            fpassthru($fp);
            exit;
        }
    }

}
